package com.example.wacoffee_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.wacoffee_user.pojo.dto.rechargeDTO;
import com.example.wacoffee_user.pojo.entity.User;
import com.example.wacoffee_user.pojo.entity.coupon;
import com.example.wacoffee_user.service.IMeService;
import com.example.wacoffee_user.utils.CurrentHoler;
import com.example.wacoffee_user.utils.JwtUtil;
import com.example.wacoffee_user.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/me")
public class meController {
    @Autowired
    private IMeService meService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public Result getMe(){
       return Result.success(meService.getMe());
    }
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        //帮我对user对象的手机号进行判断不符合规定/格式直接抛出错误
        if(!isValidPhoneNumber(user.getPhone()))throw new RuntimeException("手机号格式错误");
        User me = meService.login(user);
        if(me==null||me.getStatus()==0)throw new RuntimeException("您的账号不存在或已被禁用");
        String token = JwtUtil.generateJwt("id", me.getId());
        return Result.success(token);
    }
    private boolean isValidPhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        return phoneNumber.matches(regex);
    }

    @PutMapping("/recharge")
    public Result recharge(@RequestBody rechargeDTO rechargeDTO){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", CurrentHoler.getCurrentId()).setSql("balance=balance+"+rechargeDTO.getAmount());
        meService.update(updateWrapper);
        meService.addRechargeOrder(rechargeDTO.getAmount());
        return Result.success();
    }

    @GetMapping("/recharge")
    public Result getRechargeOrder(){
        return Result.success(meService.getRechargeOrder());
    }

    @GetMapping("/information")
    public Result getInformation(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("username","password","gender","phone","image").eq("id",CurrentHoler.getCurrentId());
        return Result.success(meService.getOne(queryWrapper));
    }
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        user.setId(CurrentHoler.getCurrentId());
        meService.updateInformationById(user);
        return Result.success();
    }

    @GetMapping("/count")
    public Result getCouponCount(){
        Integer count=meService.getCouponCount();
        return Result.success(count);
    }

    @GetMapping ("/coupon")
     public Result getMyCoupon(){
        List<coupon> coupons=meService.getMyCoupon();
        return Result.success(coupons);
    }

    @PostMapping("/sign")
    public Result sign(){
        Integer userId=CurrentHoler.getCurrentId();
        LocalDateTime now=LocalDateTime.now();
        String keyPre=now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key="sign:"+userId+":"+keyPre;
        int dayOfMonth=now.getDayOfMonth();
        if(Boolean.TRUE.equals(stringRedisTemplate.opsForValue().getBit(key, dayOfMonth - 1)))return Result.error ("今天已经签到过了");
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(result == null || result.isEmpty()) return Result.success(0);
        Long num=result.get(0);
        System.out.println(num);
        if(num == null) return Result.success(0);
        int count=0;
        while(true){
            if((num & 1) == 0){
                break;
            }else {
                count++;
                num>>>=1;
            }
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",userId).setSql("exp=exp+"+count+",point=point+"+count);
        meService.update(updateWrapper);
        meService.checkAndUpdate(CurrentHoler.getCurrentId());
        return Result.success();
    }

    @GetMapping("/sign")
    public Result getSign(){
        Integer userId=CurrentHoler.getCurrentId();
        LocalDateTime now=LocalDateTime.now();
        String keyPre=now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key="sign:"+userId+":"+keyPre;
        int dayOfMonth=now.getDayOfMonth();
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(result == null || result.isEmpty()) return Result.success(0);
        Long num=result.get(0);
        if(num == null) return Result.success(0);
        int count=0;
        while(true){
            if((num & 1) == 0){
                break;
            }else {
                count++;
                num>>>=1;
            }
        }
        return Result.success(count);
    }
}
